import { createStore } from 'vuex'
import { CHANGE_INFO } from './mutation_type'
import homeModule from './modules/home'
import counterModule from './modules/counter'

const store = createStore({
  /* state() {
		return {
			counter: 0,
		}
	}, */

  state: () => ({
    rootCounter: 2,
    name: 'coderwhy',
    level: 100,
    avaterURL: 'http://xxxx',
    freinds: [
      { id: 111, name: 'why', age: 21 },
      { id: 112, name: 'why1', age: 20 },
      { id: 113, name: 'why2', age: 22 },
    ],
  }),
  getters: {
    totalAge(state) {
      return state.freinds.reduce((pre, cur) => {
        return pre + cur.age
      }, 0)
    },

    message(state, getters) {
      return `name: ${state.name}; level: ${state.level} friendTotalAge: ${getters.totalAge}`
    },

    // 传参
    findFriendsById(state) {
      // return state.freinds.find((item) => item.id === 112)
      return function (id) {
        return state.freinds.find((item) => item.id === id)
      }
    },
  },
  mutations: {
    increment(state) {
      state.rootCounter++
    },
    incrementLevel(state) {
      state.level++
    },

    [CHANGE_INFO](state, payload) {
      state.name = payload.name
      state.level = payload.level
    },
  },

  actions: {
    incrementAction(ctx) {
      ctx.commit('increment')
    },

    changeNameAction(ctx, payload) {
      ctx.commit('changeName', payload)
    },
  },

  modules: {
    home: homeModule,
    counter: counterModule,
  },
})

export default store
